package com.roadmap.util.chart;

import java.io.IOException;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.plot.Plot;
import org.jfree.chart.servlet.ServletUtilities;
import org.jfree.data.general.Dataset;
import org.jfree.data.general.DefaultPieDataset;

import com.roadmap.common.RdcLogger;
import com.roadmap.common.RdcResourceBundle;

public class RdcDataPieChart extends DataChart {
	private final static Logger logger = RdcLogger
			.getLogger(RdcDataPieChart.class);

	public RdcDataPieChart() {
		// _title.setText(title);
		_chart = ChartFactory.createPieChart("", null, true, true, false);
		initChart(_chart);
	}

	public Dataset getTestData() {
		DefaultPieDataset data = new DefaultPieDataset();
		data.setValue("未计划", 10);
		data.setValue("已计划", 30);
		data.setValue("进行中", 10);
		data.setValue("已完成", 20);
		data.setValue("已取消", 30);

		return data;
	}

	@Override
	protected void initPlot(Plot plot) {
		if (plot == null || !(plot instanceof PiePlot)) {
			logger.error("INVALID Plot instance was input.");
			return;
		}

		PiePlot piePlot = (PiePlot) plot;
		// piePlot.setForegroundAlpha(0.9F);
		piePlot.setBackgroundPaint(_background);
		piePlot.setNoDataMessage(RdcResourceBundle.CHART_NO_DATA_MESSAGE);
		piePlot.setLabelGenerator(_labelGenerator);
		piePlot.setLabelFont(_labelFont);
		piePlot.setLabelPaint(_fontColor);
		// piePlot.setLegendLabelToolTipGenerator(_legendLabelGenerator);
		// piePlot.setSimpleLabels(true);
		piePlot.setInteriorGap(0.05D);
		piePlot.setLabelOutlinePaint(_background);
		piePlot.setLabelBackgroundPaint(_background);
		piePlot.setOutlineVisible(false);
	}

	public synchronized String convertDataSetToPNG(String title,
			Dataset dataset, int width, int height, HttpSession session)
			throws IOException {
		if (title != null) {
			_title.setText(title);
		}
		if (session == null) {
			return null;
		}

		((PiePlot) _chart.getPlot()).setDataset((DefaultPieDataset) dataset);
		String fname = ServletUtilities.saveChartAsPNG(_chart, width, height,
				session);

		if (logger.isDebugEnabled()) {
			logger.debug("saving chart to PNG completed for " + fname);
		}

		return fname;
	}

}
